﻿using FanaticRock.MediaSource.AutoBuilder;
using FanaticRock.MediaSource.BilibiliAPI.Helpers;
using FanaticRock.MediaSource.BilibiliAPI.RequestVo.Player.Wbi;
using FanaticRock.MediaSource.BilibiliAPI.ResponseDto.Player.Wbi;
using System.Text.Json;

namespace FanaticRock.MediaSource.BilibiliAPI.API.Player.Wbi
{
    public class PlayUrl
    {
        [MethodInclude]
        public static async Task<PlayUrlResponseDto> Invoke(PlayUrlRequestVo vo)
        {
            try
            {
                var httpClient = HttpClientHelper.GetHttpClient();

                var para = await vo.ToWbiParameter();
                using var requestMessage = new HttpRequestMessage(
                    method: HttpMethod.Get,
                    requestUri: $"https://api.bilibili.com/x/player/wbi/playurl?{para}");

                requestMessage.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0");

                //requestMessage.Headers.Add(name: "Cookie", value: $"SESSDATA={vo.SessData}");
                //requestMessage.Headers.Referrer = new Uri("wwww.bilibili.com");

                using var responseMessage = await httpClient.SendAsync(requestMessage);
                responseMessage.EnsureSuccessStatusCode();

                using var stream = await responseMessage.Content.ReadAsStreamAsync();
                var resultDto = await JsonSerializer.DeserializeAsync<PlayUrlResponseDto>(stream);
                //var str = await responseMessage.Content.ReadAsStringAsync();

                return resultDto;
            }
            catch (Exception ex)
            {
                return new PlayUrlResponseDto()
                {
                    Code = Enums.CodeEnum.RequestError,
                    Message = ex.ToString(),
                };
            }
        }
    }
}
